package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.biz.common.Constant;
import cn.falcon.fmobi.biz.service.AdvertiserPlatformAuditService;
import cn.falcon.fmobi.biz.service.AudienceService;
import cn.falcon.fmobi.biz.service.CustomerService;
import cn.falcon.fmobi.biz.service.StrategyService;
import cn.falcon.fmobi.biz.service.dmp.RptGdtAdGroupService;
import cn.falcon.fmobi.biz.service.dmp.RptGdtTargetingReportService;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.dao.enumration.AuditStatus;
import cn.falcon.fmobi.dao.model.SyncStrategyModel;
import cn.falcon.fmobi.dao.po.AdvertiserPlatformAudit;
import cn.falcon.fmobi.dao.po.Audience;
import cn.falcon.fmobi.dao.util.MailUtil;
import cn.falcon.marketing.api.enumeration.CustomerSystemStatus;
import cn.falcon.marketing.api.enumeration.Operator;
import cn.falcon.marketing.api.model.DateRange;
import cn.falcon.marketing.api.model.FilteringStruct;
import cn.falcon.marketing.api.model.advertiser.Advertiser;
import cn.falcon.marketing.api.model.report.DailyReportResult;
import cn.falcon.marketing.api.model.report.HourlyReportsResult;
import cn.falcon.marketing.api.model.report.ReportQuery;
import cn.falcon.marketing.api.model.report.TargetReportResult;
import cn.falcon.marketing.api.service.TokenRefreshService;
import cn.falcon.marketing.api.service.advertiser.AdvertiserServiceImpl;
import cn.falcon.marketing.api.service.advertiser.IAdvertiserService;
import cn.falcon.marketing.api.service.report.ReportServiceImpl;
import cn.falcon.marketing.api.util.JsonUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author ZhouChunhui
 * @create 2017-10-15 15:26
 **/
@Controller
@RequestMapping("/sync/gdt")
public class SyncGdtReportCtrl {

    @Autowired
    private ReportServiceImpl reportService;

    @Autowired
    private RptGdtTargetingReportService rptGdtTargetingReportService;

    @Autowired
    private RptGdtAdGroupService rptGdtAdGroupService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private IAdvertiserService advertiserService;

    @Autowired
    private AdvertiserPlatformAuditService platformAuditService;

    @Autowired
    private StrategyService strategyService;

    @Autowired
    private AudienceService audienceService;

    Logger logger = Logger.getLogger(this.getClass());

    private static String mails = "1107403188@qq.com";
    /**
     * @param date 查询报告的日期，一次查询一天
     * @param type 枚举值 可以为 GENDER, AGE, REGION
     */
    @RequestMapping(value = "/report/targeting", method = RequestMethod.GET)
    public ModelAndView syncUserAgeReport(String date, String type,@RequestParam(required = false)Integer uid) {
        List<Integer> advertiserIds;
        if(uid!=null){
            advertiserIds = new ArrayList<>();
            advertiserIds.add(uid);
        }else{
            advertiserIds = strategyService.selectSyncReportAdvertiserByPlatformId(Constant.PLATFORM_ID_TENCENT);
        }
        //2、对这些广告主进行循环
        for (Integer advertiserId : advertiserIds) {
            //查询出广告主对应的腾讯平台的ID
            try {
                AdvertiserPlatformAudit advertiserPlatformAudit = platformAuditService.selectAdvertiser(Constant.PLATFORM_ID_TENCENT,advertiserId);
                if(advertiserPlatformAudit==null) continue;
                int gdtId = advertiserPlatformAudit.getPlatformAdvertiserId();
                ReportQuery reportQuery = new ReportQuery();
                reportQuery.setAccount_id(gdtId);
                reportQuery.setType(type);
                reportQuery.setLevel("ADVERTISER");

                DateRange dateRange = new DateRange();

                dateRange.setStart_date(date);
                dateRange.setEnd_date(date);
                reportQuery.setDate_range(JsonUtil.toJson(dateRange));

                reportQuery.setGroup_by(JsonUtil.toJson(new String[] { "date" }));
                List<TargetReportResult> list = reportService.targetingTagReportsGet(reportQuery, true);

                //如果推广计划 级别可以返回推广计划ID的 。
                rptGdtTargetingReportService.saveRptTargetingReport(list, type, advertiserId, date);
            } catch (Exception e) {
                MailUtil.sendMail(mails,"同步定向标签报告异常 date："+date+";advertiserId:"+advertiserId+";type:"+type,e);
                logger.error("同步定向标签报告异常 date："+date+";advertiserId:"+advertiserId+";type:"+type + e.getMessage(), e.getCause());
            }
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 日报
     *
     * @param date 时间
     * @return
     */
    @RequestMapping(value = "/report/daily", method = RequestMethod.GET)
    public ModelAndView syncUserDailyReport(String date,@RequestParam(required = false)Integer uid) {
        try {
            List<Integer> advertiserIds;
            if(uid!=null){
                advertiserIds = new ArrayList<>();
                advertiserIds.add(uid);
            }else{
                advertiserIds = strategyService.selectSyncReportAdvertiserByPlatformId(Constant.PLATFORM_ID_TENCENT);
            }

            //2、对这些广告主进行循环
            for (Integer advertiserId : advertiserIds) {
                try {
                    //查询出广告主对应的腾讯平台的ID
                    AdvertiserPlatformAudit advertiserPlatformAudit = platformAuditService.selectAdvertiser(Constant.PLATFORM_ID_TENCENT,advertiserId);
                    if(advertiserPlatformAudit==null) continue;
                    int gdtId = advertiserPlatformAudit.getPlatformAdvertiserId();
                    ReportQuery reportQuery = new ReportQuery();
                    reportQuery.setAccount_id(gdtId);
                    reportQuery.setLevel("ADGROUP");

                    DateRange dateRange = new DateRange();

                    dateRange.setStart_date(date);
                    dateRange.setEnd_date(date);
                    reportQuery.setDate_range(JsonUtil.toJson(dateRange));

                    reportQuery.setGroup_by(JsonUtil.toJson(new String[] { "date" }));
                    List<DailyReportResult> list = reportService.getDailyReport(reportQuery, true);

                    //如果推广计划 级别可以返回推广计划ID的。
                    rptGdtAdGroupService.saveRptDailyReport(list, advertiserId, date);
                    System.err.println("all--资金账户信息：" + JsonUtil.toJson(list));
                } catch (Exception e) {
                    MailUtil.sendMail(mails,"同步分天报告异常 date："+date+";advertiserId:"+advertiserId,e);
                    logger.error("同步分天报告异常 date："+date+";advertiserId:"+advertiserId + e.getMessage(), e.getCause());
                }
            }
        } catch (Exception e) {
            MailUtil.sendMail(mails,"同步分天报告异常 date："+date,e);
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 时报
     *
     * @param date 日期
     * @param hour 小时
     * @return
     */
    @RequestMapping(value = "/report/hourly", method = RequestMethod.GET)
    public ModelAndView syncUserHourlyReport( String date, Integer hour,@RequestParam(required = false) Integer uid) {
        List<Integer> advertiserIds;
        if(uid!=null){
            advertiserIds = new ArrayList<>();
            advertiserIds.add(uid);
        }else{
            advertiserIds = strategyService.selectSyncReportAdvertiserByPlatformId(Constant.PLATFORM_ID_TENCENT);
        }

        //2、对这些广告主进行循环
        for (Integer advertiserId : advertiserIds) {
            try {
                //查询出广告主对应的腾讯平台的ID
                AdvertiserPlatformAudit advertiserPlatformAudit = platformAuditService.selectAdvertiser(Constant.PLATFORM_ID_TENCENT,advertiserId);
                if(advertiserPlatformAudit==null) continue;
                int gdtId = advertiserPlatformAudit.getPlatformAdvertiserId();
                ReportQuery reportQuery = new ReportQuery();
                reportQuery.setAccount_id(gdtId);
                reportQuery.setLevel("ADGROUP");
                reportQuery.setDate(date);

                reportQuery.setGroup_by(JsonUtil.toJson(new String[] { "hour" }));
                List<HourlyReportsResult> list = reportService.hourlyReportResultGet(reportQuery, true);

                if (list != null && list.size() > 0) {
                    rptGdtAdGroupService.saveRptHourlyReport(list, advertiserId, date, hour);
                }
            } catch (Exception e) {
                MailUtil.sendMail(mails,"同步小时报告异常 date："+date+";hour:"+hour+";advertiserId:"+advertiserId,e);
                logger.error("同步小时报告异常 date："+date+";hour:"+hour+";advertiserId:"+advertiserId + e.getMessage(), e.getCause());
            }

        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 同步广告主状态
     * @return
     */
    @RequestMapping(value = "/advertiser/status", method = RequestMethod.GET)
    public ModelAndView syncAdvertiserStatus() {
        //查询出待审核的广点通平台广告主列表。
        List<AdvertiserPlatformAudit> list = customerService
            .selectAdvertiserPendingByPlatformId(Constant.PLATFORM_ID_TENCENT);
        for (AdvertiserPlatformAudit platformAuditInfo : list) {
            try {
                Advertiser advertiser = advertiserService.getAdvertiser(platformAuditInfo.getPlatformAdvertiserId());
                boolean update = true;
                switch (advertiser.getSystem_status().name()) {
                case "CUSTOMER_STATUS_NORMAL":
                    platformAuditInfo.setAuditStatus(AuditStatus.AUDIT_STATUS_SUCCESS.getValue());
                    break;
                case "CUSTOMER_STATUS_DENIED":
                    platformAuditInfo.setAuditStatus(AuditStatus.AUDIT_STATUS_FAILURE.getValue());
                    platformAuditInfo.setAuditMsg(advertiser.getReject_message());
                    break;
                case "CUSTOMER_STATUS_FROZEN":
                    platformAuditInfo.setAuditStatus(AuditStatus.AUDIT_STATUS_FAILURE.getValue());
                    platformAuditInfo.setAuditMsg(advertiser.getReject_message());
                    break;
                default:
                    update = false;
                    break;
                }
                if (update) {
                    platformAuditService.updateAuditStatusByPlatformIdAndAdvertiserId(platformAuditInfo.getPlatformId(),
                        platformAuditInfo.getAdvertiserId(), platformAuditInfo.getAuditStatus());
                }
            } catch (Exception e) {
                MailUtil.sendMail(mails,"同步广告主状态异常ID:"+platformAuditInfo.getAdvertiserId(),e);
                logger.error("同步广告主状态异常"+JsonUtil.toJson(platformAuditInfo) + e.getMessage(), e.getCause());
            }
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 同步策略状态
     *
     * @return
     */
    @RequestMapping(value = "/strategy/status", method = RequestMethod.GET)
    public ModelAndView syncStrategyStatus() {
        // 查询待同步状态的策略
        List<SyncStrategyModel> syncList =  strategyService.listStrategyForSync();
        for (SyncStrategyModel item : syncList) {
            try {
                strategyService.syncGdtStrategy(item.getPlatformAdvertiserId(),item.getAdGroupId(),item.getStrategyId());
            } catch (Exception ex) {
                MailUtil.sendMail(mails,"同步策略状态异常ID:"+item.getStrategyId(),ex);
                logger.error(JsonUtil.toJson(item) + ex.getMessage(), ex.getCause());
            }
        }

        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 同步人群状态
     */
    @RequestMapping(value = "/audience/status", method = RequestMethod.GET)
    public ModelAndView syncAudienceStatus() {
        //1、查询审核状态为 待处理 的人群列表
        List<Audience> list = audienceService.listAudienceForSync();
        for (Audience item : list) {
            try {
                audienceService.syncAudienceStatus(item.getAdvertiserId(),item.getMarketingAudienceId());
            } catch (Exception ex) {
               MailUtil.sendMail(mails,"同步人群状态异常marketing_audience_id:"+item.getMarketingAudienceId(),ex);
                logger.error(JsonUtil.toJson(item) + ex.getMessage(), ex.getCause());
            }
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    @Autowired
    private TokenRefreshService tokenRefreshService;

    @RequestMapping(value = "/refresh/token", method = RequestMethod.GET)
    public ModelAndView refreshToken() {
        tokenRefreshService.refreshToken();
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }
}
